/*
@Desc : 提供http server
@Version : 1.0.0
@Time : 2019/6/28 11:59 
@Author : hammercui
@File : server
@Company: Sdbean
*/
package http

import (
	"github.com/bilibili/kratos/pkg/conf/paladin"
	"go-kit-starter/api"
	"net/http"

	"go-kit-starter/internal/model"
	"go-kit-starter/internal/service"

	"github.com/bilibili/kratos/pkg/log"
	bm "github.com/bilibili/kratos/pkg/net/http/blademaster"
)

var (
	svc *service.Service
	BmConfig struct {
		   Server *bm.ServerConfig
	   }
)


// New new a bm server.
func New(s *service.Service) (engine *bm.Engine) {
	if err := paladin.Get("http.toml").UnmarshalTOML(&BmConfig); err != nil {
		if err != paladin.ErrNotExist {
			panic(err)
		}
	}
	log.Info("load http config success! %+v",BmConfig.Server)

	svc = s
	engine = bm.DefaultServer(BmConfig.Server)
	initRouter(engine)
	protoModel.RegisterSearchServiceBMServer(engine,svc)
	if err := engine.Start(); err != nil {
		panic(err)
	}
	return
}

func initRouter(e *bm.Engine) {
	e.Ping(ping)
	g := e.Group("/starter")
	{
		g.GET("/start",JwtMidware, howToStart)
		g.GET("/ping",JwtMidware,ping)
	}
}

func ping(ctx *bm.Context) {
	if err := svc.Ping(ctx); err != nil {
		log.Error("ping dao error(%v)", err)
		ctx.AbortWithStatus(http.StatusServiceUnavailable)
	}
}

// example for http request handler.
func howToStart(c *bm.Context) {
	k := &model.Kratos{
		Hello: "Golang 大法好 !!!",
	}
	//c.Render(200, render.JSON{
	//	Code:    200,
	//	Message: "ok",
	//	Data:    k,
	//})
	c.Render(http.StatusOK,CustomJSON{
		Data:k,
	})
}